package com.framework.network.remote

import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers

/**
 * @ClassName: ResponseTransform
 * @Description: 对数据进行解析，将有用数据抛出
 * @Author: you
 */
@Throws(ApiException::class)
fun <T> BaseResponse<T>.handleResponse(): T {
    return when (code) {
        ApiCodeConst.CODE_SUCCESS -> {
            data ?: throw NoDataApiException()
        }
        ApiCodeConst.CODE_LOGIN_INVALID -> { //重新登录
            throw LoginInvalidApiException(msg)
        }
        else -> {
            throw ErrorApiException(code, msg)
        }
    }
}

fun <T> Single<BaseResponse<T>>.requestObserver(networkObserver: NetworkObserver<T>) {
    val observer = map { response ->
        response.handleResponse()
    }
    observer.run {
        this.observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.io())
            .subscribe(networkObserver)
    }
}
//子线程
fun <T> Single<BaseResponse<T>>.requestIoObserver(networkObserver: NetworkObserver<T>) {
    val observer = map { response ->
        response.handleResponse()
    }
    observer.run {
        this.subscribeOn(Schedulers.io())
            .subscribe(networkObserver)
    }
}

